package com.bmslz.monitorpre.job;

import com.bmslz.monitorpre.grpc.MonitorGrpcClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
@Component
public class PushDataJob {
    @Autowired
    private MonitorGrpcClient monitorGrpcClient;
    @Value("${client.project.domain}")
    private String domainsStr;

    /**
     * 测点数据推送demo
     * map中是监控模型的数据
     * 每一个key对应模型中的一个测点key,value为当前测点数据
     * Map<String, String> data = new HashMap<>();
     * data.put("cpu.use", "1");
     * data.put("mem.use", "100");
     * monitorGrpcClient.sendMetrics(data);
     * return "Metrics sent";
     */
    @Scheduled(fixedRateString = "#{${client.project.rate} * 1000}")
    public void executeTask() {
        //下面写你测点数据的获取逻辑:请求远程接口\获取本机信息\获取其他组件暴露的信息等方式都可以
        Map<String, String> map = getData();
        monitorGrpcClient.sendMetrics(map);
    }

    private Map<String, String> getData() {
        Map<String, String> map = new HashMap<>();
        String[] domainsArr = domainsStr.split(",");
        for (String domain : domainsArr) {
            log.info(domain);
            map.put(domain, String.valueOf(getData(domain)));
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return map;
    }


    private static String getData(String domain) {
        String apiUrl = "https://www.whoiscx.com/api/whois/info";
        try {
            String res = sendPostRequest(apiUrl, domain);
            return extractValueByKey(res, "valid_days");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "-1";
    }

    /**
     * 使用正则表达式从JSON中提取指定key的值
     *
     * @param json JSON字符串
     * @param key  要提取的key
     * @return key对应的值
     */
    public static String extractValueByKey(String json, String key) {
        // 构建正则表达式，匹配 "key": 后面跟着的值
        String regex = "\"" + Pattern.quote(key) + "\":\\s*\"?([^,\"}]+)\"?";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(json);

        if (matcher.find()) {
            return matcher.group(1).replace("\"", "");
        }
        return null;
    }

    /**
     * 发送POST请求到WHOIS API
     *
     * @param urlString API地址
     * @param domain    要查询的域名
     * @return API返回的JSON字符串
     * @throws Exception 如果请求或读取响应失败
     */
    private static String sendPostRequest(String urlString, String domain) throws Exception {
        String postData = "domain=" + java.net.URLEncoder.encode(domain, StandardCharsets.UTF_8.name());
        urlString = urlString+ "?" + postData;
        // 创建URL对象
        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        // 设置请求方法为POST
        connection.setRequestMethod("POST");
        connection.setDoOutput(true); // 允许输出
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Java WhoIs Client)"); // 设置User-Agent，有些服务器会检查

        // 发送请求
        try (OutputStream os = connection.getOutputStream()) {
            os.flush();
        }

        // 检查HTTP响应代码
        int responseCode = connection.getResponseCode();
        if (responseCode != HttpURLConnection.HTTP_OK) {
            throw new RuntimeException("HTTP请求失败，响应码: " + responseCode);
        }

        // 读取响应内容
        StringBuilder response = new StringBuilder();
        try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
        } finally {
            connection.disconnect();
        }
        System.out.println(response.toString());
        return response.toString();
    }

}

